import logging

from django.http import JsonResponse
from django.shortcuts import render, redirect
import string
import random
from django.core.mail import send_mail
from django.urls import reverse
from django.views.decorators.http import require_http_methods
from .blog_forms.registerForm import RegisterForm
from .blog_forms.loginForm import LoginForm
from django.contrib.auth import get_user_model, login, logout

from .models import verify_email

User = get_user_model()

# 创建日志记录器
import logging

# 创建日志记录器
logger = logging.getLogger('blog_auth')


@require_http_methods(['GET', 'POST'])
def authlogin(request):
    if request.method == 'GET':
        if request.user.is_authenticated:
            return redirect('blog:index')
        return render(request, 'login.html')
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            remember = form.cleaned_data['remember']
            user = User.objects.filter(username=username).first()
            logger.debug(f"User object: {user}")
            if user:
                password_valid = user.check_password(password)
                logger.debug(f"Password valid: {password_valid}")
                if password_valid:
                    login(request, user)
                    if not remember:
                        request.session.set_expiry(0)
                    else:
                        request.session.set_expiry(60 * 60 * 24 * 7)
                    return render(request, 'index.html')
                else:
                    logger.debug("Password does not match")
                    return JsonResponse({'code': 400, 'msg': '密码错误'})
            else:
                logger.debug("User not found")
                return JsonResponse({'code': 400, 'msg': '用户不存在'})
        else:
            logger.debug(f"Form errors: {form.errors}")
            return JsonResponse({'code': 400, 'msg': form.errors})


def authlogout(request):
    logout(request)
    request.session.flush()
    return redirect('blog:index')


@require_http_methods(['GET', 'POST'])
def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    else:
        form = RegisterForm(request.POST)
        if form.is_valid():
            User.objects.create_user(username=form.cleaned_data['username'],
                                     email=form.cleaned_data['email'],
                                     password=form.cleaned_data['password'])
            return redirect(reverse('blog_auth:authlogin'))
        return JsonResponse({'code': 400, 'msg': form.errors})


def sends_email(request):
    email = request.GET.get('email')
    if not email:
        return JsonResponse({'code': 400, 'msg': '邮箱地址为空'})

    code = ''.join(random.sample(string.digits, 4))
    verify_email.objects.update_or_create(email=email, defaults={'code': code})
    try:
        send_mail(
            '验证码邮件',
            f'您的验证码是{code}',
            from_email='835748938@qq.com',
            recipient_list=[email],
            fail_silently=False,
        )
        return JsonResponse({'code': 200, 'msg': '发送成功'})
    except Exception as e:
        return JsonResponse({'code': 500, 'msg': str(e)})
